package bsf.util;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;

/**
 * Created by chejiangyi on 2017/3/29.
 */
public class ExceptionUtil {
    public static String getFullMessage(Throwable e)
    {
        if(e == null)
            return "";
        String message = "【详细错误】" +FileUtil.lineSeparator()+ getDetailMessage(e)+FileUtil.lineSeparator()+"【堆栈打印】"+FileUtil.lineSeparator()+getFullStackTrace(e);
        return message;
    }
    public static String getFullStackTrace(Throwable e) {
        if(e == null)
            return "";
        StringWriter sw = null;
        PrintWriter pw = null;
        try {
            sw = new StringWriter();
            pw = new PrintWriter(sw);
            // 将出错的栈信息输出到printWriter中
            e.printStackTrace(pw);
            pw.flush();
            sw.flush();
        } finally {
            if (sw != null) {
                try {
                    sw.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
            if (pw != null) {
                pw.close();
            }
        }
        return sw.toString();
    }

    public static String getDetailMessage(Throwable ex) {
        if(ex == null)
            return "";
        StringBuilder sb = new StringBuilder();
        while (ex != null) {
            sb.append("【"+ex.getClass().getName()+"】→" + StringUtil.nullToEmpty(ex.getMessage()) + FileUtil.lineSeparator());
            ex = ex.getCause();
        }
        return sb.toString();
    }
}
